package main

import (
	"context"
	"fmt"
	"golang.org/x/sync/errgroup"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	_ "time"
)

func main() {
	sigs := make(chan os.Signal, 1)
	signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
	group := new(errgroup.Group)
	ctx, cancel := context.WithCancel(context.Background())
	group.Go(server1(ctx))
	group.Go(server2(ctx))
	group.Go(server3(ctx))
	go func() {
		select {
		case <-sigs:
			fmt.Println("accept signal to cancel")
			cancel()
		case <-ctx.Done():
		}

	}()
	if err := group.Wait(); err != nil {
		cancel()
		fmt.Println("Get errors:", err)
	}
}
func server1(ctx context.Context) func() error {
	return func() error {
		mux := http.NewServeMux()
		mux.HandleFunc("/", func(resp http.ResponseWriter, req *http.Request) {
			fmt.Fprintln(resp, "hello world1")
		})
		mux.HandleFunc("/do", func(resp http.ResponseWriter, req *http.Request) {
			fmt.Fprintln(resp, "do something1")
		})
		server := &http.Server{
			Addr:    "127.0.0.1:8001",
			Handler: mux,
		}
		go func() {
			select {
			case <-ctx.Done():
				fmt.Println("close1")
				server.Shutdown(ctx)
			}
		}()
		err := server.ListenAndServe()
		return err
	}

}
func server2(ctx context.Context) func() error {
	return func() error {
		mux := http.NewServeMux()
		mux.HandleFunc("/", func(resp http.ResponseWriter, req *http.Request) {
			fmt.Fprintln(resp, "hello world2")
		})
		mux.HandleFunc("/do", func(resp http.ResponseWriter, req *http.Request) {
			fmt.Fprintln(resp, "do something2")
		})
		server := &http.Server{
			Addr:    "127.0.0.1:8002",
			Handler: mux,
		}
		go func() {
			select {
			case <-ctx.Done():
				fmt.Println("close2")
				server.Shutdown(ctx)
			}
		}()
		err := server.ListenAndServe()
		return err
	}

}
func server3(ctx context.Context) func() error {
	return func() error {
		mux := http.NewServeMux()
		mux.HandleFunc("/", func(resp http.ResponseWriter, req *http.Request) {
			fmt.Fprintln(resp, "hello world3")
		})
		mux.HandleFunc("/do", func(resp http.ResponseWriter, req *http.Request) {
			fmt.Fprintln(resp, "do something3")
		})
		server := &http.Server{
			Addr:    "127.0.0.1:8003",
			Handler: mux,
		}
		go func() {
			select {
			case <-ctx.Done():
				fmt.Println("close3")
				server.Shutdown(ctx)
			}
		}()
		err := server.ListenAndServe()
		return err
	}
}
